package com.example.ecas.service.impl;

import com.example.ecas.common.CommonResponse;
import com.example.ecas.service.GetFilesService;
import org.apache.commons.io.FileUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Objects;

@Service
public class GetFilesServiceImpl implements GetFilesService {

    @Override
    public File storeFile(MultipartFile f, String outputDir) throws IOException {
        //创建目标文件夹对象
        File saveDir = new File(outputDir);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }
        //将multipartFile存储，即转换为File
        File file=new File(saveDir, Objects.requireNonNull(f.getOriginalFilename()));

//        multipartFile.transferTo(file);
        FileUtils.copyInputStreamToFile(f.getInputStream(),file);//复制流，与上一式子有哪些不同？

        return file;
    }

    @Override
    public CommonResponse<Object> identifyImage(File file,String pythonFilePath,String targetFile) throws IOException {
        //        File file=new File("D:\\practiseTraining\\ecas\\workspace\\python\\test.jpg");
//        String outputDir="D:\\practiseTraining\\ecas\\workspace\\python\\files";
//        String pythonFilePath="D:\\practiseTraining\\ecas\\workspace\\python\\ocr.py";
        String msg="";
        Process proc;

        String fileName=file.getName();
//                BufferedImage image = ImageIO.read(file);

        //获取支持的图片格式
        String supportString= Arrays.toString(ImageIO.getWriterFileSuffixes());
        String supportFormatString=supportString.substring(1,supportString.length()-1);
        String []supportFormat=supportFormatString.split(",");

        //获取目标文件格式
        String imgFormat=fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());

        boolean flag=true;

        //判断是否满足图片格式
        for(String s:supportFormat){
            s=s.trim();
            if (imgFormat.equals(s)){
                flag=false;
                break;
            }
        }

        //不满足图片格式
        if(flag){
            msg="仅支持"+supportFormatString+"图片格式";
//           System.out.println(msg);
            return CommonResponse.creatForError(msg);
        }

        StringBuilder content= new StringBuilder("");
        //执行python脚本并输出图片内容
        try {

            String[] args1 = new String[] { "python",
                    pythonFilePath,
                    targetFile};

            //识别内容

            proc=Runtime.getRuntime().exec(args1);

            //用输入输出流来截取结果

            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                content.append(line).append("\n");
            }
            in.close();
            proc.waitFor();

            //判断删除是否成功
            if (!new File(targetFile).delete()){
                System.out.println("删除失败");
            }

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            msg="OCR识别异常";
//           System.out.println(msg);
            return CommonResponse.creatForError(msg);
        }

//        System.out.println(content);

        return CommonResponse.creatForSuccess(content.toString());



    }

    @Override
    public CommonResponse<Object> identifyPDF(File file) throws IOException {
        String fileName = file.getName();
        String imgFormat = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
        String msg="";

        if (!imgFormat.equals("pdf")) {
            msg="此文件非PDF";
//            System.out.println(msg);
            return CommonResponse.creatForError(msg);

        }

        PDDocument doc = PDDocument.load(file);

        //判断为图片性pdf
        if(doc.isEncrypted()) {
            msg="该pdf为图片型pdf,暂不提供该服务";
//            System.out.println(msg);
            return CommonResponse.creatForError(msg);
        }

        int pagenum=doc.getNumberOfPages();
//                FileOutputStream fos=new FileOutputStream(outputPath);
//                Writer writer=new OutputStreamWriter(fos,"UTF-8");
        PDFTextStripper stripper=new PDFTextStripper();
        stripper.setSortByPosition(true);
        stripper.setStartPage(0);
        stripper.setEndPage(pagenum);
        String content=stripper.getText(doc);
        doc.close();

        if(!file.delete()){
            System.out.println("文件删除失败");
        }

        return CommonResponse.creatForSuccess(content);
    }
//                writer.close();
}
